package com.itheima.aspect;//package com.itheima.aspect;

import com.itheima.anno.Log;
import com.itheima.anno.LogOperation;
import com.itheima.mapper.OperateEmpMapper;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.*;
import com.itheima.utils.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

@Aspect
@Component
public class OperationEmpLogAspect {

    @Autowired
    private OperateEmpMapper operatorEmpMapper;

    // 环绕通知
    @Around("@annotation(log)")
    public Object around(ProceedingJoinPoint joinPoint, Log log) throws Throwable {
        // 记录开始时间
         long startTime = System.currentTimeMillis();
        // 构建日志对象
        EmpLoginLog  empLoginLog = new  EmpLoginLog();
        // 执行方法
        Object result = null;
        try {
            result = joinPoint.proceed();

            Result res = (Result) result;
            // 获取参数
            Object[] args = joinPoint.getArgs();
            //获取用户名和密码
            Emp map = (Emp) args[0];
            String username =  map.getUsername();
            String password = map.getPassword();
            LoginInfo loginInfo = ( LoginInfo)res.getData();

            //设置是否成功
            empLoginLog.setIsSuccess((short)1);
            //获取id
            empLoginLog.setId(loginInfo.getId());
            empLoginLog.setUsername(username);
            empLoginLog.setPassword(password);
            // 设置登录时间
            empLoginLog.setLoginTime(LocalDateTime.now());
            //获取token
            empLoginLog.setJwt(loginInfo.getToken());
        } catch (Throwable e) {
            empLoginLog.setIsSuccess((short)0);
            throw e;
        }finally {

            // 当前时间
            long endTime = System.currentTimeMillis();
            // 耗时
            long costTime = endTime - startTime;
            // 设置耗时
            empLoginLog.setCostTime(costTime);

            // 插入日志
            operatorEmpMapper.insertEmp(empLoginLog);
        }

        return result;
    }
}
